package com.neusoft.elmboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.neusoft.elmboot.util.RSAUtils;
import com.neusoft.elmboot.util.TokenUtils;

import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.util.RSAUtils;

@RestController
@RequestMapping("/users")
public class UserController {
	
	@Autowired
	private UserService userService;
    
	RSAUtils rsaUtils=new  RSAUtils();
	
	@PostMapping("/authenticate")
	public User getUserByIdByPass(User user) throws Exception{
		// 使用私钥解密用户密码
		//String password=user.getPassword();
		String password=rsaUtils.rsa_endjiemi(userService.getPrivateKey(user.getUserId()),user.getPassword());
		user.setPassword(rsaUtils.md5jiami(password,user.getUserId()));
		// 返回找到的用户对象	
		return userService.getUserByIdByPass(user);
	}
	
	@PostMapping("/{userId}")
	public String getUserById(User user) throws Exception{
	    int flag=userService.getUserById(user.getUserId());
	    //判断用户是否存在
	    if(flag==0) {
	    	//返回公钥
	    	String[]keysBase64=rsaUtils.rsa_jiami(user);
	    	user.setPublicKey(keysBase64[0]);
	    	user.setPrivateKey(keysBase64[1]);
	    	userService.saveKey(user);
	    	return keysBase64[0]; 
	    }
	    else return "1";
	}
	
	@PostMapping("")
	public int saveUser(User user) throws Exception{
		//String password=user.getPassword();
		String password=rsaUtils.rsa_endjiemi(userService.getPrivateKey(user.getUserId()),user.getPassword());
		user.setPassword(rsaUtils.md5jiami(password,user.getUserId()));
		return userService.saveUser(user);
	}
	

	@GetMapping("/key/{userId}")
	public String getPublicteKey(User user) throws Exception{
		return userService.getPublicKey(user.getUserId());
	}
	
	
	@PutMapping("/{userId}")
	public int updateUser(User user)  throws Exception{
		//String password=user.getPassword();
		if(user.getPassword()==null||user.getPassword()=="") {}
		else {
			String password=rsaUtils.rsa_endjiemi(userService.getPrivateKey(user.getUserId()),user.getPassword());
			user.setPassword(rsaUtils.md5jiami(password,user.getUserId())); 
				
		}
		return userService.updateUser(user);
	}
	
	
	@GetMapping("/all/{userId}")
	public User getEntireUserById(User user) {
		return userService.getEntireUserById(user.getUserId());
	}
	
	
	
}


